package com.cens.mall.ware.service.impl;

import com.cens.common.constant.WareConstant;
import com.cens.mall.ware.entity.PurchaseDetailEntity;
import com.cens.mall.ware.service.PurchaseDetailService;
import com.cens.mall.ware.service.WareSkuService;
import com.cens.mall.ware.vo.MergeVo;
import com.cens.mall.ware.vo.PurchaseFinishVo;
import com.cens.mall.ware.vo.PurchaseItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cens.common.utils.PageUtils;
import com.cens.common.utils.Query;

import com.cens.mall.ware.dao.PurchaseDao;
import com.cens.mall.ware.entity.PurchaseEntity;
import com.cens.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceived(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
                        .in("status", "0", "1")
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        List<Integer> itemIds = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntities = itemIds.stream()
                .map(
                        itemId -> {
                            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                            purchaseDetailEntity.setId(itemId.longValue());
                            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                            return purchaseDetailEntity;
                        }
                ).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailEntities);
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void received(List<Long> ids) {
        List<PurchaseEntity> purchaseEntities = ids.stream()
                .map(this::getById)
                .filter(
                        item -> item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode() ||
                                item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                )
                .peek(
                        item -> item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode())
                )
                .collect(Collectors.toList());
        this.updateBatchById(purchaseEntities);
        purchaseEntities.forEach(
                item -> {
                    List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.getByPurchaseId(item.getId());
                    List<PurchaseDetailEntity> detailEntities = purchaseDetailEntities.stream()
                            .map(
                                    purchaseDetailEntity -> {
                                        PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                                        detailEntity.setId(purchaseDetailEntity.getId());
                                        detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                                        return detailEntity;
                                    }
                            ).collect(Collectors.toList());
                    purchaseDetailService.updateBatchById(detailEntities);
                }
        );
    }

    @Override
    public void done(PurchaseFinishVo finishVo) {
        Long purchaseId = finishVo.getId();

        List<PurchaseItemVO> items = finishVo.getItems();
        boolean flag = items.stream().allMatch(
                item -> item.getStatus() == WareConstant.PurchaseDetailStatusEnum.FINISH.getCode()
        );
        List<PurchaseDetailEntity> purchaseDetailEntities = items.stream()
                .map(
                        item -> {
                            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                            purchaseDetailEntity.setStatus(item.getStatus());
                            purchaseDetailEntity.setId(item.getItemId());
                            return purchaseDetailEntity;
                        }
                ).collect(Collectors.toList());
        items.stream()
                .filter(item -> item.getStatus() == WareConstant.PurchaseDetailStatusEnum.FINISH.getCode())
                .forEach(
                        item -> {
                            PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(item.getItemId());
                            wareSkuService.addStock(
                                    purchaseDetailEntity.getSkuId(),
                                    purchaseDetailEntity.getWareId(),
                                    purchaseDetailEntity.getSkuNum()
                            );
                        }
                );
        purchaseDetailService.updateBatchById(purchaseDetailEntities);
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HAS_ERROR.getCode());
        this.updateById(purchaseEntity);
    }

}